package work.view;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import work.model.Address;

public class AddressEditDialogController {
	
	@FXML
	private TextField ipField;
	@FXML
	private TextField portField;
	
	private Stage dialogStage;
	private Address address;
	private boolean okClicked = false;
	
	@FXML
	private void initialize() {
		
	}
	
	public void setDialogStage(Stage dialogStage) {
		this.dialogStage = dialogStage;
	}
	
	public void setAddress(Address address) {
		this.address = address;
		
		ipField.setText(address.getIp());
		portField.setText(address.getPort());
	}
	
	public boolean isOkClicked() {
		return okClicked;
	}
	
	@FXML
	private void handleOk() {
		if(isInputValid()) {
			address.setIp(ipField.getText());
			address.setPort(portField.getText());
			
			okClicked = true;
			dialogStage.close();
		}
	}
	
	@FXML
	private void handleCancel() {
		dialogStage.close();
	}
	
	private boolean isInputValid() {
		System.out.println("Good");
		String errorMessage = "";
		
		if(ipField.getText()==null||ipField.getText().length()==0) {
			errorMessage += "No valid ip!";
		}
		
		if(portField.getText()==null||portField.getText().length()==0) {
			errorMessage += "No valid port!";
		}
		
		if(errorMessage.length()==0) {
			return true;
		}
		else {
			
			Alert alert = new Alert(AlertType.ERROR);
			alert.setTitle("Error Dialog");
			alert.setHeaderText("Invalid Fields");
			alert.setContentText("Please correct invalid fields!");
			
			alert.showAndWait();
			
			return false;
		}
		
	}
	
}
